# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.


from odoo import api, fields, models, tools, _
import datetime

# 客户表 上 做 开票客户
#
# 退货订单
#   明细行为负数
# 正常销售订单
#   明细行为正数


class SaleOrder(models.Model):
    _name = "fp.sale.order"
    _description = "FP Sales Order"
    _order = 'date_order desc, id desc'

    invoice_type = fields.Selection(
        selection=[
            # ('vat_fapiao', '增值税发票'),  # 草稿状态时, 增值税发票的类型待定
            ('vat_special', '增值税专用发票'),
            ('vat_general', '增值税普通发票'),
            ('vat_general_e', '增值税电子普通发票'),
            ('vat_special_e', '增值税电子专用发票'),
            # ('40', '货物运输业增值税专用发票'),
            # ('50', '机动车销售统一发票'),
            # ('60', '卷式发票'),
            # ('70', '二手车发票'),
            # ('80', '通行费发票'),
        ], default='vat_general_e')

    name = fields.Char(
        string='Order Number', required=True, copy=False, readonly=True,
        states={'draft': [('readonly', False)]}, index=True,
        default=lambda self: _('New'))

    client_order_ref = fields.Char(
        string='Customer Reference', copy=False,
        help="业务系统的主键")

    company_id = fields.Many2one(
        'res.company', 'Company', required=True, index=True,
        default=lambda self: self.env.company)

    user_id = fields.Many2one(
        'res.users', string='User', index=True, default=lambda self: self.env.user)

    state = fields.Selection([
        ('draft', 'Draft'),
        ('confirmed', 'Confirmed'),
        ('done', 'Locked'),
        ('cancel', 'Cancelled'),
    ], string='Status', readonly=True, copy=False, index=True, default='draft')

    date_order = fields.Datetime(
        string='Order Date', required=True, readonly=True,
        index=True,
        states={'draft': [('readonly', False)]},
        copy=False, default=fields.Datetime.now,
        help="")

    partner_id = fields.Many2one(
        'fp.biz.partner', string='Customer', readonly=True,
        states={'draft': [('readonly', False)]},
        required=True, index=True)

    fp_partner_id = fields.Many2one(
        'fp.partner', string='Fapiao Partner',
        related="partner_id.fp_partner_id")

    note = fields.Text()

    amount_untaxed = fields.Float(
        string='Untaxed Amount', compute='_amount_all', store=True)
    amount_tax = fields.Float(
        string='Tax', compute='_amount_all', store=True)
    amount_total = fields.Float(
        string='Total',  compute='_amount_all', store=True)

    amount_untaxed_discount = fields.Float(
        string='Untaxed Discount Amount', compute='_amount_all', store=True)
    amount_tax_discount = fields.Float(
        string='Tax Discount', compute='_amount_all', store=True)
    amount_discount = fields.Float(
        string='Discount',  compute='_amount_all', store=True)

    line_ids = fields.One2many(
        'fp.sale.order.line', 'order_id', string='Order Lines',
        states={'cancel': [('readonly', True)], 'done': [('readonly', True)]}, copy=True, auto_join=True)

    fapiao_ids = fields.Many2many(
        'fp.fapiao', compute='_compute_fapiao_ids')

    @api.depends('line_ids.fapiao_line_ids')
    def _compute_fapiao_ids(self):
        for order in self:
            fapiao_ids = order.line_ids.mapped(
                'fapiao_line_ids').mapped('fapiao_id')
            order.fapiao_ids = fapiao_ids

    @api.depends('line_ids.amount_total')
    def _amount_all(self):
        for order in self:
            amount_untaxed = amount_tax = 0.0
            amount_untaxed_discount = amount_tax_discount = 0.0

            for line in order.line_ids:
                amount_untaxed += line.amount_untaxed
                amount_tax += line.amount_tax
                amount_untaxed_discount += line.amount_untaxed_discount
                amount_tax_discount += line.amount_tax_discount

            amount_untaxed = round(amount_untaxed, 2)
            amount_tax = round(amount_tax, 2)
            amount_untaxed_discount = round(amount_untaxed_discount, 2)
            amount_tax_discount = round(amount_tax_discount, 2)

            order.update({
                'amount_untaxed': amount_untaxed,
                'amount_tax': amount_tax,
                'amount_total': round(amount_untaxed + amount_tax, 2),
                'amount_untaxed_discount': amount_untaxed_discount,
                'amount_tax_discount': amount_tax_discount,
                'amount_discount': round(amount_untaxed_discount + amount_tax_discount, 2)
            })

    def _update_name(self):
        for one in self:
            if not one.name or one.name == _('New'):
                now = datetime.datetime.now()
                now1 = now.strftime('%Y%m%d')
                one.name = now1 + str(one.id).rjust(12, '0')

    @api.model_create_multi
    def create(self, vals_list):
        records = super().create(vals_list)
        records._update_name()
        return records

    def action_confirm(self):
        self2 = self.search([('id', 'in', self.ids), ('state', '=', 'draft')])
        for one in self2:
            one.write({'state': 'confirmed'})

    def action_cancel(self):
        self2 = self.search([('id', 'in', self.ids),
                             ('state', 'in', ['draft', 'confirmed'])])

        for one in self2:
            one.write({'state': 'cancel'})

    def action_draft(self):
        self2 = self.search([('id', 'in', self.ids), ('state', '=', 'cancel')])
        for one in self2:
            one.write({'state': 'draft'})

    def action_done(self):
        self2 = self.search([('id', 'in', self.ids),
                             ('state', 'in', ['draft', 'confirmed'])])
        for one in self2:
            one.write({'state': 'done'})


class SaleOrderLine(models.Model):
    _name = 'fp.sale.order.line'
    _inherit = ['fp.sale_line.mixin']

    _description = 'FP Sales Order Line'
    _order = 'order_id, order_num, sequence, id'

    order_id = fields.Many2one(
        'fp.sale.order', string='Order Reference',
        required=True, ondelete='cascade', index=True, copy=False)

    company_id = fields.Many2one(
        related='order_id.company_id', string='Company', store=True, index=True)

    order_partner_id = fields.Many2one(
        related='order_id.partner_id', store=True, string='Customer', index=True)

    state = fields.Selection(
        related='order_id.state', string='Order Status', copy=False, store=True)

    client_line_ref = fields.Char(
        string='Customer Reference', copy=False,
        help="业务系统的主键")

    order_num = fields.Char('NC订单号')

    name = fields.Text(string='Description', required=True)
    sequence = fields.Integer(string='Sequence', default=10)
    note = fields.Text()

    fapiao_line_ids = fields.Many2many(
        'fp.fapiao.line',
        'fp_fapiao_line_to_sale_rel',
        'sale_line_id', 'fapiao_line_id',
        string="Fapiao Lines", readonly=True, copy=False,)
